﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace EFDemo
{
    public class Deadlock
    {
        public static void RunWithThread()
        {
            var dl = new Deadlock();
            var t1 = new Thread(dl.doWork1);
            t1.Name = "Thread-1";
            t1.Start();
            var t2 = new Thread(dl.doWork2);
            t2.Name = "Thread-2";
            t2.Start();

            t1.Join();
            t2.Join();
            Console.WriteLine("Main Thread Done");
        }

        private object lock1 = new object();
        private object lock2 = new object();

        public void doWork1()
        {
            WriteCurrentThreadInfo("acquiring lock1.");
            lock (lock1)
            {
                WriteCurrentThreadInfo("== acquired lock1. done");
                Thread.Sleep(1000 * 10);

                WriteCurrentThreadInfo("acquiring lock2.");
                lock (lock2)
                {
                    WriteCurrentThreadInfo("== acquired lock2 done.");
                    Thread.Sleep(1000 * 10);
                }
            }
        }

        public void doWork2()
        {
            WriteCurrentThreadInfo("acquiring lock2.");
            lock (lock2)
            {
                WriteCurrentThreadInfo("== acquired lock2 done.");
                Thread.Sleep(1000 * 10);

                WriteCurrentThreadInfo("acquiring lock1.");
                lock (lock1)
                {
                    WriteCurrentThreadInfo("== acquired lock1 done.");
                    Thread.Sleep(1000 * 10);
                }
            }
        }

        private void WriteCurrentThreadInfo(string msg)
        {
            Console.WriteLine("[{2}][{0}] {1}", Thread.CurrentThread.Name, msg, DateTime.Now);
        }
    }
}
